package com.yangye.niodemo.netty.self;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.junit.Test;

import java.net.InetSocketAddress;

/**
 * @author yangye
 * @date 2020/12/24
 */
public class MyNetty {

	class User {
		String username;
		int age;

		public User(String username, int age) {
			this.username = username;
			this.age = age;
		}
	}
	@Test
	public void test() {
//		User user = new User("name", 11);
		// 标量替换
		String name = "name";
		int age = 11;
		// 栈上分配，hotspot
		// JIT即时编译
	}

	@Test
	public void clientTest() throws InterruptedException {
		NioEventLoopGroup group = new NioEventLoopGroup(1);

		NioSocketChannel client = new NioSocketChannel();

		group.register(client);
		ChannelPipeline pipeline = client.pipeline();
		pipeline.addLast(new MyInHandler());

		ChannelFuture connect = client.connect(new InetSocketAddress("192.168.28.200", 9090));
		// 等待连接成功
		connect.sync();

		ByteBuf buf = Unpooled.copiedBuffer("hello server".getBytes());
		ChannelFuture send = client.writeAndFlush(buf);
		// 等待发送成功
		send.sync();

		// 等待断开
		connect.channel().closeFuture().sync();

		System.out.println("client closed...");
	}

	@Test
	public void serverTest() throws InterruptedException {
		NioEventLoopGroup group = new NioEventLoopGroup(1);
		NioServerSocketChannel server = new NioServerSocketChannel();

		group.register(server);

		// 处理pipeline
		ChannelPipeline p = server.pipeline();
		p.addLast(new MyAcceptHandler(group, new MyInHandler()));

		ChannelFuture bind = server.bind(new InetSocketAddress(9090));
		bind.sync().channel().closeFuture().sync();
		System.out.println("server closed...");

	}
}
